<template>
  <div class="app-container home">
    <el-row>
      <el-col :span="6">
        <el-card class="box-card" style="width: 95%; height: 150px">
          <div slot="header" class="clearfix">
            <span>用户统计</span>
          </div>
          <div class="text item">
            <span>用户总数：{{ homePage.sumUserNumber }}</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card" style="width: 95%; height: 150px">
          <div slot="header" class="clearfix">
            <span>设备总数：{{ homePage.sumDevNumber }}</span>
          </div>
          <div class="text item">
            <span style="display: block"
              >在线数：{{ homePage.onLineDevNumber }}</span
            >
            <span style="display: block"
              >离线数： {{ homePage.offlineDevNumber }}
            </span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card" style="width: 95%; height: 150px">
          <div slot="header" class="clearfix">
            <span>能耗统计：4013.935</span>
          </div>
          <div class="text item">
            <span style="display: block">本年：0</span>
            <span style="display: block">本月：0</span>
            <span style="display: block">本日：0</span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="box-card" style="width: 95%; height: 150px">
          <div slot="header" class="clearfix">
            <span>异常统计</span>
          </div>
          <div class="text item">
            <span>异常消息： {{ homePage.exDevCount }}</span>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <el-row></el-row>
    <el-row>
     <el-col :span="6">
      <el-form  :inline="true">
        <el-form-item label="在线设备" prop="devGroupId">
          <el-select v-model="onlineDevMac" placeholder="请选择在线设备" clearable filterable 
            @visible-change="getOnlineMacList($event)"
            :style="{ width: '180px' }">
            <el-option v-for="item in onlineDevList" :key="item.devMac" :label="item.devMac"
              :value="item.devMac"></el-option>
          </el-select>
        </el-form-item>
        <el-button type="primary" @click="changeMacAndInitEcharts()">查 看</el-button>
      </el-form>
      </el-col>
      <el-col :span="3" :offset="15">
        <el-form  :inline="true">
          <el-button-group label="模式切换">
            <!-- style="font-size: 25px; padding: 5px 15px" -->
            <el-button :type="realtimeBtnType" @click="changePollingMode('REALTIME')" >实 时</el-button>
            <el-button :type="regularBtnType" @click="changePollingMode('REGULAR')">定 时</el-button>
          </el-button-group>
          
        </el-form>
      </el-col>
    </el-row>
    
    <el-row style="display: none">
      <div class="searchItem">
        <el-input
          :style="{ width: '200px' }"
          class="searchInput inputDeep input__inner"
          v-model="searchDevId"
          placeholder="请输入设备编号"
          clearable
          ref="searchInput"
          @mouseenter.native="searchMouseoverOpt"
          @mouseout.native="searchMouseoutOpt"
          @focus="searchFocusOpt"
          @blur="searchBlurOpt"
        >
        </el-input>
        <div
          :style="{
            lineHeight: inputHeight + 'px',
            width: inputHeight + 'px',
            height: inputHeight + 'px',
            left: inputWidth - 3 + 'px',
          }"
          class="el-icon-search searchBtn"
          ref="searchBtn"
          @click="searchBtnOpt"
        ></div>
      </div>
    </el-row>
    <el-row>
      <!-- <el-row>
        <el-col :span="12">
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <div ref="useElectricity" style="height: 220px" />
          </div>
        </el-col>
        <el-col :span="12">
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <div ref="voltage" style="height: 220px" />
          </div>
        </el-col>
      </el-row> -->
      <el-row>
        <el-col :span="12">
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <div ref="current" style="height: 220px" />
          </div>
        </el-col>
        <el-col :span="12">
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <div ref="power" style="height: 220px" />
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <div ref="voltage" style="height: 220px" />
          </div>
        </el-col>
        <el-col :span="12">
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <div ref="frequency" style="height: 220px" />
          </div>
        </el-col>
        <!-- <el-col :span="12">
          <div class="el-table el-table--enable-row-hover el-table--medium">
            <div ref="powerFactor" style="height: 220px" />
          </div>
        </el-col> -->
      </el-row>
    </el-row>
  </div>
</template>

<script>
import {
  findDevInfoByMac,
  findDevHomePageChart,
  querHomePage,
  getOnlineMac,
  changePollingMode,
} from "@/api/alm/home/home";
import * as echarts from "echarts";

export default {
  name: "Index",
  data() {
    return {
      searchDevId: "",
      timerDevId: "",
      inputHeight: "",
      buttonHeight: "",
      inputWidth: "",
      continueOpt: false,
      devInfoList: [],
      getDevInfoTimer: null,
      homePage: {
        sumUserNumber: "",
        sumDevNumber: "",
        onLineDevNumber: "",
        offlineDevNumber: "",
        elecount: "",
        exDevCount: "",
      },
      // 轮询周期 单位ms 定时前端5200ms，实时1000ms，定时时设备实际上传间隔为4s
      pollingTime: 5000,
      onlineDevList: [],
      onlineDevMac: null,
      // 记录当前的设备mac
      devMacRecord: null,
      queryDevMac: null,
      pollingMode: "",
      queryParams: {
        devMac: ""
      },

      changeModeParams: {
        devMac: '',
        changeCode: ''
      },

      // 按钮颜色切换参数
      regularBtnType: 'success',
      realtimeBtnType: 'info',

    };
  },
  created() {
    this.querHomePage();
    this.createdOnlineDevMacList();
    // this.loadTimer();
  },
  mounted() {
    this.getControlInfo();
    // this.loadTimer();
  },
  methods: {
    querHomePage() {
      querHomePage().then((response) => {
        this.homePage.sumUserNumber = response.data.sumUserNumber;
        this.homePage.sumDevNumber = response.data.sumDevNumber;
        this.homePage.onLineDevNumber = response.data.onLineDevNumber;
        this.homePage.offlineDevNumber = response.data.offlineDevNumber;
        this.homePage.elecount = response.data.elecount;
        this.homePage.exDevCount = response.data.exDevCount;
      });
    },

    getOnlineMacList(callback) {
      if(callback == true) {
        getOnlineMac().then(res => {
          this.onlineDevList = res.data;
          // 如果无数据this.devMacRecord所记录的mac地址需清除
          if(this.onlineDevList == undefined || this.onlineDevList == null || this.onlineDevList.length < 1) {
            this.devMacRecord = null;
          }
        })
      }
      
    },

    createdOnlineDevMacList() {
      getOnlineMac().then(res => {
        this.onlineDevList = res.data;
        if(this.onlineDevList.length > 0) {
          this.pollingMode = this.onlineDevList[0].pollingMode;
          this.onlineDevMac = this.onlineDevList[0].devMac;

          this.queryDevMac = this.onlineDevMac;

          this.devMacRecord = this.onlineDevMac;
          // 判断pollingMode
          if(this.pollingMode == "REALTIME") {
            this.pollingTime = 1000;
            // 实时/定时按钮颜色修改
            this.realtimeBtnType = 'success';
            this.regularBtnType = 'info';

          }else {
            this.pollingTime = 5000;
            // 实时/定时按钮颜色修改
            this.realtimeBtnType = 'info';
            this.regularBtnType = 'success';

          }
          
          this.loadTimer();
        }
      })
    },

    changeMacAndInitEcharts() {
      console.log(this.onlineDevMac)
        this.queryDevMac = this.onlineDevMac
      // mac不同才初始化数据
      if(this.devMacRecord != this.queryDevMac) {
        this.devInfoList = [];
        // 遍历对象，匹配
        var len = this.onlineDevList.length;
        for(var i = 0; i < len; i ++) {
          if(this.queryDevMac  == this.onlineDevList[i].devMac) {
            this.pollingMode = this.onlineDevList[i].pollingMode;
          }
        }
        // 判断pollingMode
        if(this.pollingMode == "REALTIME") {
          
          // 实时/定时按钮颜色修改
          this.realtimeBtnType = 'success';
          this.regularBtnType = 'info';
          // 轮询周期
          this.pollingTime = 1000;

        }else {
          // 实时/定时按钮颜色修改
          this.realtimeBtnType = 'info';
          this.regularBtnType = 'success';
          // 轮询周期
          this.pollingTime = 5000;
        }
        // 干掉原来的轮询
        clearInterval(this.getDevInfoTimer);

        this.devMacRecord = this.queryDevMac;
        // 调用接口
        this.loadTimer();
      }
      
    },

    // 实时/定时按钮的方法
    changePollingMode(pollingMode) {
      this.changeModeParams.devMac = this.onlineDevMac;
      this.changeModeParams.changeCode = pollingMode;
      this.pollingMode = pollingMode;
      console.log(this.changeModeParams)
      // 不需要清除数据，需要重置轮询
      changePollingMode(this.changeModeParams).then(res => {
        console.log(res);
        if(res.code == 200) {
          if(this.pollingMode == "REALTIME") {
            
            this.pollingTime = 1000;
            // 实时/定时按钮颜色修改
            this.realtimeBtnType = 'success';
            this.regularBtnType = 'info';

          }else {
            this.pollingTime = 5000;
            // 实时/定时按钮颜色修改
            this.realtimeBtnType = 'info';
            this.regularBtnType = 'success';

          }
          // 干掉原来的轮询
          clearInterval(this.getDevInfoTimer);

          // 重置下拉框
          getOnlineMac().then(record => {
            this.onlineDevList = record.data;
            // 调用接口
            this.loadTimer();
          })

        }
      })
    },

    getvoltage() {
      if (!echarts.getInstanceByDom(this.$refs.voltage)) {
        this.voltage = echarts.init(this.$refs.voltage, "macarons");
      }

      let timeArr = [];
      let infoArr = [];
      this.devInfoList.forEach((item) => {
        timeArr.push(this.dateFormat(item.modifyTime / 1000));
        infoArr.push(item.avgVoltage);
      });
      this.voltage.setOption(
        this.forMatterMapInfo(
          "当前电压",
          timeArr,
          "V",
          infoArr,
          "#607bca"
        ),
        0.1
      );
      window.addEventListener("resize", () => {
        this.voltage.resize();
      });
    },

    getCurrent() {
      if (!echarts.getInstanceByDom(this.$refs.current)) {
        this.current = echarts.init(this.$refs.current, "macarons");
      }
      let timeArr = [];
      let infoArr = [];
      this.devInfoList.forEach((item) => {
        timeArr.push(this.dateFormat(item.modifyTime / 1000));
        infoArr.push(item.electricCurrent);
      });
      this.current.setOption(
        this.forMatterMapInfo(
          "当前电流",
          timeArr,
          "A",
          infoArr,
          "#93cd77"
        ),
        0.01
      );
      window.addEventListener("resize", () => {
        this.current.resize();
      });
    },

    getPower() {
      if (!echarts.getInstanceByDom(this.$refs.power)) {
        this.power = echarts.init(this.$refs.power, "macarons");
      }
      let timeArr = [];
      let infoArr = [];
      this.devInfoList.forEach((item) => {
        timeArr.push(this.dateFormat(item.modifyTime / 1000));
        infoArr.push(item.avgPowerFactor);
      });
      this.power.setOption(
        this.forMatterMapInfo(
          "当前功率",
          timeArr,
          "W",
          infoArr,
          "#fac859"
        ),
        0.1
      );
      window.addEventListener("resize", () => {
        this.power.resize();
      });
    },

    getFrequency() {
      if (!echarts.getInstanceByDom(this.$refs.frequency)) {
        this.frequency = echarts.init(this.$refs.frequency, "macarons");
      }
      let timeArr = [];
      let infoArr = [];
      this.devInfoList.forEach((item) => {
        timeArr.push(this.dateFormat(item.modifyTime / 1000));
        infoArr.push(item.avgFrequency);
      });
      this.frequency.setOption(
        this.forMatterMapInfo(
          "平均频率",
          timeArr,
          "Hz",
          infoArr,
          "#f4b3da"
        ),
        0.1
      );
      window.addEventListener("resize", () => {
        this.frequency.resize();
      });
    },

    // getPowerFactor() {

    //   if (!echarts.getInstanceByDom(this.$refs.powerFactor)) {
    //     this.powerFactor = echarts.init(this.$refs.powerFactor, "macarons");
    //   }
    //   let timeArr = [];
    //   let infoArr = [];
    //   this.devInfoList.forEach(item => {
    //     timeArr.push(this.dateFormat(item.modifyTime / 1000))
    //     infoArr.push(item.powerFactor)
    //   })
    //   this.powerFactor.setOption(this.forMatterMapInfo('功率因数', timeArr, 'PF', infoArr));
    //   window.addEventListener("resize", () => {
    //     this.powerFactor.resize();
    //   });
    // },

    searchFocusOpt() {
      this.$refs.searchBtn.classList.add("searchBorder");
      this.$refs.searchBtn.classList.remove("searchBorderByHover");
    },

    searchBlurOpt() {
      this.$refs.searchBtn.classList.remove("searchBorder");
    },

    searchMouseoverOpt() {
      for (let _class of this.$refs.searchBtn.classList) {
        if (_class === "searchBorder") {
          return;
        }
      }
      this.$refs.searchBtn.classList.add("searchBorderByHover");
    },

    searchMouseoutOpt() {
      this.$refs.searchBtn.classList.remove("searchBorderByHover");
    },

    searchBtnOpt() {
      // if (!this.searchDevId) {
      //   this.$message.warning('请输入正确的设备编号');
      //   return
      // }
      this.timerDevId = this.searchDevId;
      findDevInfoByMac(this.searchDevId).then((devInfo) => {
        if (devInfo.data != null) {
          this.devInfoList = [];
          this.devInfoList.push(devInfo.data);
          // this.getUseElectricity();
          this.getvoltage();
          this.getCurrent();
          this.getPower();
          this.getFrequency();
          // this.getPowerFactor();
        } else {
          this.$message.error("该设备未在线或不存在");
        }
      });
    },

    getControlInfo() {
      this.inputHeight = this.$refs.searchInput.$el.offsetHeight;
      this.inputWidth = this.$refs.searchInput.$el.offsetWidth;
      this.buttonHeight = this.$refs.searchBtn.offsetHeight;
      console.log("this.$refs.searchInput ", this.$refs.searchInput);
      console.log("this.$refs.searchBtn ", this.buttonHeight);
    },

    forMatterMapInfo(
      titleSubtext,
      xAxisData,
      yAxisAxisLabelFormatter,
      seriesData,
      randomColor,
      miny
    ) {
      return {
        title: {
          text: " ",
          subtext: titleSubtext,
        },
        tooltip: {
          trigger: "axis",
          axisPointer: {
            type: "cross",
          },
        },
        toolbox: {
          show: true,
          feature: {
            saveAsImage: {},
          },
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          // prettier-ignore
          data: xAxisData,
        },
        yAxis: {
          type: "value",
          min: miny,
          axisLabel: {
            formatter: "{value} " + yAxisAxisLabelFormatter,
          },
          axisPointer: {
            snap: true,
          },
        },
        visualMap: {
          show: false,
          dimension: 0,
          pieces: [
            {
              gt: 0,
              lte: 19,
              color: randomColor,
            },
          ],
        },
        series: [
          {
            name: titleSubtext,
            type: "line",
            smooth: true,
            // prettier-ignore
            data: seriesData,
            markArea: {
              itemStyle: {
                color: "rgba(255, 173, 177, 0.4)",
              },
              data: [],
            },
          },
        ],
      };
    },

    dateFormat(timeStamp) {
      // 创建一个新的Date对象，将时间戳作为参数传递给构造函数
      const date = new Date(timeStamp * 1000);
      // 获取年、月、日、小时和分钟
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      const seconds = String(date.getSeconds()).padStart(2, "0");
      // 重新赋值格式化后的日期字符串
      return `${year}/${month}/${day} ${hours}:${minutes}:${seconds}`;
    },
    loadShow() {
      
      if (true) {

        let params = {};
        params.devMac = this.queryDevMac;

        //2024.07.03由查询所有总数据改为查询单设备信息
        findDevHomePageChart(params).then((devInfo) => {
          if (devInfo.data != null) {
            // console.log('devInfo ', devInfo);
            if (this.devInfoList.length > 9) {
              this.devInfoList.splice(0, 1);
              if (devInfo.data.avgVoltage == null) {
                devInfo.data.avgVoltage = 0;
              }
              if (devInfo.data.electricCurrent == null) {
                devInfo.data.electricCurrent = 0;
              }
              if (devInfo.data.avgFrequency == null) {
                devInfo.data.avgFrequency = 0;
              }
              if (devInfo.data.avgPowerFactor == null) {
                devInfo.data.avgPowerFactor = 0;
              }
              this.devInfoList.push(devInfo.data);
            } else {
              this.devInfoList.push(devInfo.data);
            }
            // _this.getUseElectricity();
            this.getvoltage();
            this.getCurrent();
            this.getPower();
            this.getFrequency();
            // _this.getPowerFactor();
          }
        });
      }
    },
    loadTimer() {
      this.loadShow();
      this.getDevInfoTimer = setInterval(this.loadShow.bind(this), this.pollingTime);
      // clearInterval(timerId);
    },

    getRandomColor() {
      const letters = "0123456789ABCDEF";
      let color = "#";
      for (let i = 0; i < 6; i++) {
        color += letters[Math.floor(Math.random() * 16)];
      }
      return color;
    },
  },
};
</script>

<style scoped lang="scss">
.el-row{
  margin-bottom: 20px;
}

.searchItem {
  margin: 20px 0;
}

.searchBtn {
  position: absolute;
  background-color: #ffffff;
  border: #dcdfe6 solid 1px;
  transition: border-color 0.3s ease;
  border-top-right-radius: 3px;
  border-bottom-right-radius: 3px;
  text-align: center;
  color: #c0c4cc;
}

.searchBtn:hover {
  cursor: pointer;
}

.test {
  border: #0550ff solid 1px;
}

.searchBorder {
  color: #409eff;
  border: #1890ff solid 1px;
}

.searchBorderByHover {
  border: #c0c4cc solid 1px;
}

.box-card {
    width: 450px;
    height: 60px;
  }
</style>
